# -*- coding: utf-8 -*-

import requests
import json
import datetime
import random

import base64


def access_token(base_url, app_key, app_secret):
    api = API(base_url)
    res = api.authen_token(app_key, app_secret)
    return res


class API(object):
    def __init__(self, base_url, app_key=None, app_secret=None, token=None, tin=None):
        self.base_url = base_url
        self.app_key = app_key
        self.app_secret = app_secret
        self.access_token = token
        self.tin = tin

    def json_call(self, url, params=None, data=None):
        if not params:
            params = {}
        if not data:
            data = {}

        base_url = self.base_url
        # timeout = self.timeout

        full_url = base_url + url

        headers = {"content-type": "application/json",
                   #    "credentials": "include"
                   }

        print('json call:', full_url, params, data)

        rspd = requests.post(full_url, params=params,
                             data=json.dumps(data),
                             headers=headers)

        # print(full_url, params, data)

        res = json.loads(rspd.text)
        print('res:', res,  type(res))

        return res

    def authen_token(self, app_key, app_secret):
        url = '/api/authen/token'

        params = {}
        data = {
            "appKey": app_key,
            "appSecret": app_secret,
        }

        res = self.json_call(url, params=params, data=data)
        return res

    def _call(self, url, content):
        url2 = url + '?access_token=' + self.access_token
        # print('_call', url2)
        print('_call,,', content)

        zipCode = '0'
        encryptCode = '0'

        now = datetime.datetime.now()
        id_yyyymmddhhmmssffffff = now.strftime("%Y%m%d%H%M%S%f")[0:17]
        random_int = random.randint(0, 1000 * 1000 * 1000 * 1000 * 1000)
        random_str = '%015d' % random_int
        dataExchangeId = id_yyyymmddhhmmssffffff+random_str

        entCode = self.tin
        json_content = json.dumps(content)
        content = base64.b64encode(json_content.encode('utf-8'))
        content = content.decode('utf-8')

        # print('base64,,', content)

        params = {}
        data = {
            'zipCode': zipCode,
            'encryptCode': encryptCode,
            'dataExchangeId': dataExchangeId,
            'entCode': entCode,
            'content': content,
        }

        # print(data)

        res = self.json_call(url2, params, data)

        returnStateInfo = res['returnStateInfo']
        returnCode = returnStateInfo['returnCode']
        returnMessage = returnStateInfo['returnMessage']
        returnMessage = base64.b64decode(returnMessage)
        returnMessage = returnMessage.decode('utf-8')

        # 'returnStateInfo': {'returnCode': '0000',
        # 'returnMessage': '5aSE55CG5oiQ5YqfIQ=='},
        # 'entCode': '12100000400002435L'}

        if returnCode != '0000':
            print('returnCode', type(returnCode),  returnCode)
            print('returnMessage', type(returnMessage),  returnMessage)

            raise Exception({
                'code': returnCode,
                'message': returnMessage
            })

        # print('ok', res)

        returnContent = res['content']
        returnContent = base64.b64decode(returnContent)
        returnContent = returnContent.decode('utf-8')
        returnContent = json.loads(returnContent)
        # print('returnContent', returnContent)
        # print('returnContent', type(returnContent), returnContent)
        print('returnContent', type(returnContent), returnContent)

        return returnContent

    def check_invoice_single(self, content):
        url = '/api/open-recipt/V1/CheckInvoiceSingle'
        # print(content)
        res = self._call(url, content)

        # res = check_invoice_single_return

        # print('check_invoice_single ok:', res)

        return_code = res['code']
        if return_code != '0000':
            raise Exception({
                'code': return_code,
                'message': res['message']
            })

        data = res['data']

        return data


check_invoice_single_return = {
    'success': True, 'code': '0000', 'message': 'default success',
    'data': {
        'detailList': [
            {
                'lx': '', 'fyxm': '', 'txrqq': '', 'txrqz': '', 'cph': '',
                'se': '25.88', 'sl': '13%',
                'mxbh': '1',
                'hwmc': '*文具*天章(TANGO) 施工监理日志日记记录本日记工地施工日志 通用单位工程项目记录记事本 施工安',
                'je': '199.12',
                'spsl': '5.00000000',
                'bhsdj': '39.82300885',
                'ggxh': '监理日志',
                'jldw': '套',
                'hsdj': '',
                'hsje': '',
                'ssflbm': '1060401990000000000'
            },
            {
                'lx': '', 'fyxm': '', 'txrqq': '', 'txrqz': '', 'cph': '', 'se': '-16.73', 'sl': '13%',
                'mxbh': '2',
                'hwmc': '*文具*天章(TANGO) 施工监理日志日记记录本日记工地施工日志 通用单位工程项目记录记事本 施工安',
                'je': '-128.72', 'spsl': '', 'bhsdj': '', 'ggxh': '', 'jldw': '', 'hsdj': '', 'hsje': '',
                'ssflbm': '1060401990000000000'
            },
            {
                'lx': '', 'fyxm': '', 'txrqq': '', 'txrqz': '', 'cph': '',
                'se': '0.34', 'sl': '6%', 'mxbh': '3', 'hwmc': '*物流辅助服务*配送费',
                'je': '5.66', 'spsl': '1.00000000', 'bhsdj': '5.66037736', 'ggxh': '无', 'jldw': '次', 'hsdj': '', 'hsje': '',
                'ssflbm': '3040409030000000000'
            }
        ],
        'cyjg': '0001', 'cyjgxx': '查验成功发票一致',
        'fpdm': '011002100111', 'fphm': '15159313', 'kprq': '20211105', 'jym': '56183922060040110881',
        'fpje': '76.06',
        'fpzl': '10', 'cjhj': '',
        'jshj': '85.55',
        'cycs': '4',
        'xhfmc': '北京京东达锐贸易有限公司',
        'xhfsbh': '91110112MA01831F9A',
        'xhfdzdh': '北京市通州区物流基地兴贸二街16号8007室 010-57807000',
        'xhfyhzh': '交通银行股份有限公司北京海淀支行 110060576018800039919',
        'gmfyhzh': '', 'gmfdzdh': '',
        'gmfmc': '河南晟华工程管理有限公司张家口分公司',
        'gmfsbh': '91130703MA0DNJRM8K',
        'fpse': '9.49',
        'bz': '订单号:229485836626', 'skph': '',
        'jqbh': '661619946800', 'kpr': '', 'skr': '', 'fhr': '',
        'bswjurl': '', 'zfbz': 'N', 'sfzh': '', 'cllx': '', 'cpxh': '',
        'cd': '', 'hgzs': '', 'sjdh': '', 'fdjhm': '', 'clsbh': '',
        'jkzmsh': '', 'zgswjgdm': '', 'wspzhm': '', 'xcrs': '',
        'zgswjgmc': '', 'dw': '', 'sl': '', 'khyh': '', 'khzh': '',
        'cyrmc': '', 'cyrsbh': '', 'spfmc': '', 'spfshb': '', 'shrmc': '',
        'shrsbh': '', 'fhrmc': '', 'fhrsbh': '', 'yshwxx': '',
        'qydjyddd': '', 'czch': '', 'ccdw': '', 'txfbz': '', 'lslbs': '',
        'cpzh': '', 'djzh': '', 'zrdcgsmc': '', 'mfdwgr': '',
        'mfdwdmsfzh': '', 'mfdwgrdz': '', 'mfdh': '', 'smfdwgr': '',
        'smfdwdmsfzh': '', 'smfdwgrzz': '', 'smfdh': '', 'jypmdw': '',
        'jypmdwdz': '', 'khyhjzh': '', 'jypmdwdh': '', 'jypmdwdzsbh': '',
        'escsc': '', 'escscdz': '', 'escsckhyhzh': '', 'escscdh': '',
        'escscsbh': '', 'qdbz': 'N', 'xhfdz': '', 'dzzfbs': ''
    }
}
